'use client';

import { type ChangeEvent, type FormEvent, useEffect, useState } from 'react';
import { useMutation } from '@tanstack/react-query';
import diff from 'microdiff';
import type { IConfigRegister, IDifference } from '@/interfaces';
import { updateRegisterConfig } from '@/services/api';
import useToast from '@/hooks/useToast';
import { getDiffData } from '@/lib/tool';
import Box from '@/app/[locale]/admin/common/box';
import Spinner from '@/app/[locale]/component/spinner/spinner';
import type { PrefixedTTranslatedFields } from '@/lib/dictionaries';

export default function UpdateConfigRegister({
  source,
  translatedFields,
}: {
  source: IConfigRegister;
  translatedFields: PrefixedTTranslatedFields<'configAdminPage'>;
}) {
  const { show } = useToast();
  const [form, setForm] = useState<{
    enableRegistrationConsent: boolean;
    terms?: string;
    privacyPolicy?: string;
  }>({
    enableRegistrationConsent: source.enableRegistrationConsent ?? false,
    terms: source.terms ?? '',
    privacyPolicy: source.privacyPolicy ?? '',
  });
  const [differenceData, setDifferenceData] = useState<IDifference[]>([]);
  const [isDisabledSave, setIsDisabledSave] = useState(true);

  const updateRegisterConfigMutation = useMutation(updateRegisterConfig);

  useEffect(() => {
    const diffData = diff(
      {
        enableRegistrationConsent: source.enableRegistrationConsent ?? false,
        terms: source.terms ?? '',
        privacyPolicy: source.privacyPolicy ?? '',
      },
      form,
    );
    setDifferenceData(diffData);
    setIsDisabledSave(diffData.length === 0);
  }, [form, source]);

  async function onClickSave(e: FormEvent<HTMLFormElement>) {
    try {
      e.preventDefault();
      e.stopPropagation();

      const data = getDiffData(differenceData);
      await updateRegisterConfigMutation.mutateAsync({
        data,
      });

      show({
        type: 'SUCCESS',
        message: translatedFields.operate.updateCompleted,
      });
    } catch (e) {
      updateRegisterConfigMutation.reset();
      show({
        type: 'DANGER',
        message: e,
      });
    } finally {
      setDifferenceData([]);
    }
  }

  function onChangeForm(e: ChangeEvent<HTMLInputElement | HTMLSelectElement>) {
    const name = e.target.name;
    const value = e.target.value;

    if (name === 'enableRegistrationConsent') {
      setForm({ ...form, enableRegistrationConsent: value === 'true' });
    } else {
      setForm({ ...form, [name]: value });
    }
  }

  return (
    <Box>
      <form onSubmit={onClickSave} className="vstack gap-4">
        <div>
          <label className="form-label">
            {translatedFields.register.enableRegistrationConsent}
          </label>
          <select
            name="enableRegistrationConsent"
            value={form.enableRegistrationConsent + ''}
            onChange={onChangeForm}
            className="form-select"
            aria-label="enableRegistrationConsent"
          >
            <option value="true">true</option>
            <option value="false">false</option>
          </select>
        </div>

        <div>
          <label className="form-label">
            {translatedFields.register.termsAddress}
          </label>
          <input
            type="text"
            className="form-control"
            name="terms"
            value={form.terms}
            onChange={onChangeForm}
            aria-describedby="terms"
          />
        </div>

        <div>
          <label className="form-label">
            {translatedFields.register.privacyPolicyAddress}
          </label>
          <input
            type="text"
            className="form-control"
            name="privacyPolicy"
            value={form.privacyPolicy}
            onChange={onChangeForm}
            aria-describedby="privacyPolicy"
          />
        </div>

        <button
          type="submit"
          disabled={updateRegisterConfigMutation.isLoading || isDisabledSave}
          className="btn btn-success col col-lg-2 my-4"
        >
          {updateRegisterConfigMutation.isLoading && <Spinner classs="me-2" />}
          {translatedFields.operate.update}
        </button>
      </form>
    </Box>
  );
}
